package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.CompanyEmployee;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyEmployeeService;
import com.xuanzheng.company.service.impl.CompanyEmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/getEmployeeDetail")
public class GetEmployeeDetailServlet extends HttpServlet {

    private CompanyEmployeeService companyEmployeeService = new CompanyEmployeeServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // System.out.println("GetEmployeeDetailServlet: 开始处理请求");
        
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(new Gson().toJson(result));
            // System.out.println("GetEmployeeDetailServlet: 用户未登录");
            return;
        }
        
        User currentUser = (User) session.getAttribute("user");
        String companyId = currentUser.getCompanyId();
        
        // System.out.println("GetEmployeeDetailServlet: 当前用户ID=" + currentUser.getId() + ", 公司ID=" + companyId);
        
        if (companyId == null || companyId.isEmpty()) {
            result.put("success", false);
            result.put("message", "您尚未加入公司");
            out.print(new Gson().toJson(result));
            // System.out.println("GetEmployeeDetailServlet: 用户未加入公司");
            return;
        }
        
        // 获取员工ID或用户ID
        String employeeId = request.getParameter("id");
        String userId = request.getParameter("userId");
        
        // System.out.println("GetEmployeeDetailServlet: 接收参数 - employeeId=" + employeeId + ", userId=" + userId);
        
        CompanyEmployee employee = null;
        
        // 先尝试通过员工ID查询
        if (employeeId != null && !employeeId.trim().isEmpty()) {
            // System.out.println("GetEmployeeDetailServlet: 通过员工ID查询");
            employee = companyEmployeeService.getEmployeeDetail(employeeId);
        } 
        // 如果没有员工ID或查询失败，尝试通过用户ID查询
        else if (userId != null && !userId.trim().isEmpty()) {
            // System.out.println("GetEmployeeDetailServlet: 通过用户ID查询");
            // 先获取用户在公司的记录
            employee = companyEmployeeService.getByUserId(userId);
            
            // 如果找到了员工记录，再获取详细信息
            if (employee != null) {
                // System.out.println("GetEmployeeDetailServlet: 找到用户的员工记录，ID=" + employee.getId());
                employee = companyEmployeeService.getEmployeeDetail(employee.getId());
            }
        } else {
            result.put("success", false);
            result.put("message", "员工ID或用户ID不能为空");
            out.print(new Gson().toJson(result));
            // System.out.println("GetEmployeeDetailServlet: 员工ID和用户ID均为空");
            return;
        }
        
        if (employee == null) {
            result.put("success", false);
            result.put("message", "找不到该员工");
            out.print(new Gson().toJson(result));
            // System.out.println("GetEmployeeDetailServlet: 找不到员工");
            return;
        }
        
        // 检查是否是同一公司的员工
        if (!employee.getCompanyId().equals(companyId)) {
            result.put("success", false);
            result.put("message", "您无权查看该员工信息");
            out.print(new Gson().toJson(result));
            // System.out.println("GetEmployeeDetailServlet: 无权查看，员工公司ID=" + employee.getCompanyId());
            return;
        }
        
        // 添加调试日志
        // System.out.println("GetEmployeeDetailServlet: 员工ID=" + employee.getId());
        // System.out.println("GetEmployeeDetailServlet: 员工姓名=" + employee.getUserName());
        // System.out.println("GetEmployeeDetailServlet: 员工身份证=" + (employee.getUserIdCard() != null ? "已设置" : "未设置"));
        
        // 手动添加掩码身份证字段
        if (employee.getUserIdCard() != null && !employee.getUserIdCard().isEmpty()) {
            String maskedIdCard = maskIdCard(employee.getUserIdCard());
            // System.out.println("GetEmployeeDetailServlet: 掩码后身份证=" + maskedIdCard);
            result.put("maskedIdCard", maskedIdCard);
        }
        
        result.put("success", true);
        result.put("employee", employee);
        result.put("isManager", currentUser.getRole() == 1); // 判断是否是公司负责人
        
        // 判断是否是公司负责人查看自己的信息
        boolean isManagerViewingSelf = currentUser.getRole() == 1 && employee.getUserId().equals(currentUser.getId());
        result.put("isManagerSelf", isManagerViewingSelf); // 添加标识，表示是否是负责人查看自己的信息
        
        // 判断员工是否是负责人
        boolean isEmployeeManager = "负责人".equals(employee.getPosition());
        result.put("isEmployeeManager", isEmployeeManager); // 添加标识，表示员工是否是负责人
        
        // System.out.println("GetEmployeeDetailServlet: 请求处理完成");
        out.print(new Gson().toJson(result));
    }
    
    // 身份证号脱敏处理，将中间10位替换为*号
    private String maskIdCard(String idCard) {
        if (idCard == null || idCard.length() < 15) return idCard;
        
        // 对于18位身份证
        if (idCard.length() == 18) {
            return idCard.substring(0, 4) + "**********" + idCard.substring(14);
        }
        
        // 对于15位身份证
        if (idCard.length() == 15) {
            return idCard.substring(0, 3) + "*********" + idCard.substring(12);
        }
        
        // 其他情况，只显示前4位和后4位
        // 其他情况，只显示前4位和后4位
        int starCount = idCard.length() - 8;
        String stars = String.format("%" + starCount + "s", "").replace(' ', '*');
        return idCard.substring(0, 4) + stars + idCard.substring(idCard.length() - 4);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
} 